

// # 服务器端的 Socket
// # 创建 socket 
// # 启动 socket 服务器 
// # 绑定端口和 IP 
// # 接收来自客户端的请求 接收来自客户端的数据 
// # 转发消息给其他的客户端 
// # 监听客户端关闭

const ws  = require("ws")
const host = "localhost"
const port = 3800
const wss = new ws.WebSocketServer({port}); // socket 创建成功

console.log("webSocket is listen at " + port)
const querystring = require("querystring")
let  count = 0;
const info = "WUHAN_2107_";
const onLineUsers = {}

// 接收来自客户端的链接请求
wss.on("connection",function(ws){
    // ws 客户端socket 
    console.log(querystring.stringify(ws)+ "上线了...");
    count++;
    ws.name = info+count;
    onLineUsers[ws.name] = ws;

    // 接收来自客户端的数据  
    ws.on("message",msg=>{
      // console.log(msg)
      // # 转发消息给其他的客户端 
      boradcast(ws,msg)
    })

    // # 监听客户端关闭
    ws.on("close",function(){
      delete onLineUsers[ws.name];  // 删除对象的某一个值  key 
      boradcast(ws,'886,我先下线了哦...');
    })

    ws.on("error",function(){
      console.log("客户端出现异常...")
    })
})

function boradcast(socket,msg){
    for(var key in onLineUsers){
      var time  = new Date();
      var hour = time.getHours()
      var min = time.getMinutes()
      onLineUsers[key].send(`${socket.name} (${hour}:${min}) 说: ${msg}`)
    }
}